const Koa = require('koa')
console.log(Koa);
const app = new Koa()
const logger = require('koa-logger')
const json = require('koa-json')
const views = require('koa-views')
const onerror = require('koa-onerror');

const index = require('./routes/index');
const users = require('./routes/users');

const FrameSyncExecutor = require("./control/FrameSyncExecutor").FrameSyncExecutor
const frameSyncExecutor = new FrameSyncExecutor()

const cors = require('koa2-cors')
app.use(cors())
// 子服务
const server = require('http').createServer(app.callback())
const socket = require('./socket/index').socket(server, frameSyncExecutor)
server.listen(process.env.PORT || 3036, () => {
  console.log(`app run at : http://127.0.0.1:${3036}`);
})

setInterval(() => {
  frameSyncExecutor.onSyncOneFrameHandler(socket)
}, 1000)

// error handler
onerror(app);

// global middlewares
app.use(views('views', {
  root: __dirname + '/views',
  default: 'jade'
}));
app.use(require('koa-bodyparser')());
app.use(json());
app.use(logger());

app.use(function* (next) {
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});

app.use(require('koa-static')(__dirname + '/public'));


// routes definition
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app;
